<!-- 功能管理页面 -->
<script setup lang='ts'>
import {reactive, ref, onMounted, computed, PropType} from 'vue'
import {HeaderData} from '@/components/dTable/dTable'
import  dDialog  from '@/components/dDialog/dDialog.vue'
import {FormRules, ElMessage} from 'element-plus'
import type {ElForm} from 'element-plus'
import dTable from '@/components/dTable/dTable.vue'
import operation from '@/components//dTable/components/operation.vue'
import { SearchFromItem, SearchButton} from '@/components/dTable/dHeader'
import { ColorRed, ColorTheme } from '@/api/config'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import { inspectItemList, inspectItemListAdd, InspectItemListAdd, inspectItemSave } from '@/api/instrument/Inspection'
const emits = defineEmits(['cancel', 'confirm', 'close'])
const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },
  gpId:{
    type:String,
    required:true
  },
  tableData:{
    type:Object as PropType<Array<any>>,
    required:true
  }
})
// const itemId = ref<any>('0')

const itemId = computed(() => {
  return props.gpId
})

const poptableData = reactive(props.tableData)

const formData = ref<any>({
  instrumentId:itemId.value,
  inspectItemType:null,
  keywords:''
})

// 操作栏配置项
const operationData = [
  {name:'del', label:'删除', iconConfig:{icon:'common-swap-reduce', type:'custom', color:ColorRed, size:20}}
]

// 操作栏配置项
const operationDatas = [
  {name:'add', label:'添加', iconConfig:{icon:'common-swap-add', type:'custom', color:ColorTheme, size:20}}
]

//左侧显示数据
const tableData = ref<Array<any>>([])
//左侧真实数据
const tableDataReal = ref<Array<InspectItemListAdd>>([])

//右侧显示数据
const tableData2 = ref<Array<any>>([])

//右侧真实数据
const tableData2Real = ref<Array<InspectItemListAdd>>([])



// 按钮搜索配置
const serachButtons = ref<Array<SearchButton>>([
  {type:'search'}
])

const idarr = ref<any>([])
//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {prop:'itemCode', label:'检验项目编码', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'itemName', label:'检验项目名称', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'operation', label:'操作', columnType:'slot', 'min-width':'50', fixed:'right'}
])



//表格数据
const tableHeaderData2 = ref<Array<HeaderData>>([
  {prop:'itemCode', label:'检验项目编码', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'itemName', label:'检验项目名称', columnType:'text', align:'center', 'min-width':'100'},
  {prop:'operation', label:'操作', columnType:'slot', 'min-width':'50', fixed:'right'}
])

// 筛选区功能
const searchFromItems = ref<Array<SearchFromItem>>(
  [
    {label:'检验项目', placeholder:'请输入检验项目', type:'input', prop:'value', enterSubmit:true, style:{width:'250px'}}
  ]
)

const searchFromData = reactive<any>({value:''})

const searchFromRules = reactive<FormRules>({
  value:[
    {required:false, message:'长度应小于50个字符', max:50, trigger: ['change', 'blur']}
  ]
})

// 筛选区功能
const searchFromItems2 = ref<Array<SearchFromItem>>(
  [
    {label:'检验项目', placeholder:'请输入检验项目', type:'input', prop:'keywords', enterSubmit:true, style:{width:'250px'}}
  ]
)

const searchFromData2 = reactive<any>({keywords:'', inspectItemType:null})

const searchFromRules2 = reactive<FormRules>({
  keywords:[
    {required:false, message:'长度应小于50个字符', max:50, trigger: ['change', 'blur']}
  ]
})

// // 根据条件查询所有子项
// const IfinspectItemListAdd = () => {
//   const str:Array<string> = []
//   poptableData.map(item => {
//     if (item.id) {
//       str.push(item.id)
//     }
//   })
//   // exceptIds:idarr.value.join(',')
//   inspectItemListAdd({exceptIds:str.join(','), inspectItemType:formData.value.inspectItemType, keywords:formData.value.keywords}).then(res => {
//     res.data.data.map(item => {
//       item.operation = operationDatas
//     })
//     tableData2.value = res.data.data
//     tableData2Real.value = tableData2Real.value.concat(res.data.data)
//     // tableData2Real.value = res.data.data
//   })
// }
// 根据条件查询所有子项
const IfinspectItemListAdd = () => {
  const str:Array<string> = []
  poptableData.map(item => {
    if (item.id) {
      str.push(item.id)
    }
  })
  // exceptIds:idarr.value.join(',')
  inspectItemListAdd({instrumentId:itemId.value, checkType:'2'}).then(res => {
    res.data.data.map(item => {
      item.operation = operationDatas
    })
    tableData2.value = res.data.data
    tableData2Real.value = tableData2Real.value.concat(res.data.data)
    // tableData2Real.value = res.data.data
  })
}
// 查询接口
const Ifinstrumentpage = () => {
  inspectItemList({instrumentId:itemId.value}).then(res => {
    res.data.data.records.map(item => {
      item.operation = operationData
      idarr.value.push(item.id)
    })
    IfinspectItemListAdd()
    tableData.value = res.data.data.records
    tableDataReal.value = res.data.data.records
  })
}



// 保存接口
const IfsetInspectItem = () => {
  const str = <Array<string>>[]
  tableDataReal.value.map(item => {
    str.push(item.id)
  })
  inspectItemSave({instrumentId:itemId.value, inspects:str}).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
      emits('confirm')
    }
  })
}


const fuzzyQuery = (list:any, keyWord:any, Select:string) => {
  if (!keyWord && !Select) {
    return list
  }
  const arr = <any>[]
  list.map((item, index) => {
    let flag = false
    for (const key in item) {
      if (key === 'itemName' || key === 'itemCode' || key === 'inspectItemType') {
        if (keyWord && Select) {
          if ((item['itemName'].toLowerCase().indexOf(keyWord.toLowerCase()) !== -1 || item['itemCode'].toLowerCase().indexOf(keyWord.toLowerCase()) !== -1) && item['itemType'].toLowerCase().indexOf(Select) !== -1) {
            flag = true
            break
          }
        } else {
          if (keyWord && item[key].toLowerCase().indexOf(keyWord.toLowerCase()) !== -1 && (key === 'itemName' || key === 'itemCode')) {
            flag = true
            break
          }
          if (!flag && Select && item[key].toLowerCase().indexOf(Select) !== -1 && key === 'inspectItemType') {
            flag = true
            break
          }
        }

      }
    }
    if (flag) {
      arr.push(item)
    }
  })
  return arr
}


// 弹窗取消
const oncancel = () => {
  emits('cancel')
  // searchFromItems.value[0].value = ''
  // searchFromItems2.value[0].value = ''
}
// 弹窗关闭
const onClose = () => {
  emits('close')
}
// 弹窗保存
const onConfirm = () => {
  IfsetInspectItem()
}

// 操作栏点击
const onOperation = (e) => {
  console.log('点击', e)

}

// 操作栏点击
const onErtion = (e, row) => {
  row.operation = operationDatas
  tableData.value.splice(tableData.value.indexOf(row), 1)
  tableDataReal.value.splice(tableDataReal.value.indexOf(row), 1)
  tableData2.value.unshift(row)
  tableData2Real.value.unshift(row)
}
// 操作栏点击
const onErtions = (e, row) => {
  row.operation = operationData

  if (!row.antibioticId) {
    row.antibioticId = row.id
  }
  row.antibioticGroupId = itemId.value
  tableData2.value.splice(tableData2.value.indexOf(row), 1)
  tableData2Real.value.splice(tableData2Real.value.indexOf(row), 1)
  tableData.value.unshift(row)
  tableDataReal.value.unshift(row)

}

// 针对于原始数据进行去重处理
const fuzzyQuerys = (list:any, keyWord:any) => {
  if (!keyWord) {
    return list
  }
  const arr = <any>[]
  list.map((item, index) => {
    let flag = false
    for (const key in item) {
      if ((key === 'itemName' || key === 'itemCode') && item[key].toLowerCase().indexOf(keyWord.toLowerCase()) !== -1) {
        flag = true
        break
      }
    }
    if (flag) {
      arr.push(item)
    }
  })
  return arr
}

const onSubmit = () => {
  // tableData.value =  fuzzyQuerys(tableDataReal.value, searchFromData.value)
  tableData.value =  [...new Set(fuzzyQuerys(tableDataReal.value, searchFromData.value))]
  // tableData.value =  JSON.parse(JSON.stringify(fuzzyQuerys(tableDataReal.value, searchFromData.value)))
}
const onSubmits = () => {
  tableData2.value =  [...new Set(fuzzyQuery(tableData2Real.value, searchFromData2.keywords, searchFromData2.inspectItemType))]
}
//行点击回调
const onRowClick = (row) => {
  console.log('行', row)
}

// 生命周期
onMounted(() => {
  IfinspectItemListAdd()
  // Ifinstrumentpage()

})
</script>

<template>
  <d-Dialog :title="'新增检验项目'" :show-dialog="showDialog" @cancel="oncancel" @close="onClose" @confirm="onConfirm">
    <div class="box">
      <div :style="{height:'580px',width:'45%',marginRight:'2%',paddingRight:'2%',borderRight:'6px solid var(--d-color-grey)'}">
        <d-table-promote
          class=".d-common-flex-full"
          style="min-height:500px;"
          :oper-buttons="[]"
          :label-width="80"
          :search-form-items="searchFromItems"
          :search-buttons="serachButtons"
          :table-data="tableData"
          :table-header-data="tableHeaderData"
          :table-head-height="40"
          :table-row-height="40"
          :show-footer="false"
          :search-from-justify="'flexStart'"
          :search-form-data="searchFromData"
          :search-rules="searchFromRules"
          @form-submit="onSubmit"
          @operation="onOperation"
          @row-click="onRowClick"
        >
          <template #operation="scope">
            <operation :row="scope.row" :col="scope.item" :force-show-button="true" @opertion-click="onErtion" />
          </template>
          <template #operbutton-append>
            <div class="titlestyle">
              已选检验项目
            </div>
          </template>
        </d-table-promote>
      </div>
      <div style="flex:1">
        <d-table-promote
          class=".d-common-flex-full"
          style="min-height:500px;"
          :oper-buttons="[]"
          :label-width="80"
          :search-form-items="searchFromItems2"
          :search-buttons="serachButtons"
          :table-data="tableData2"
          :table-header-data="tableHeaderData2"
          :show-footer="false"
          :search-from-justify="'flexStart'"
          :search-form-data="searchFromData2"
          :search-rules="searchFromRules2"
          @form-submit="onSubmits"
          @operation="onOperation"
          @row-click="onRowClick"
        >
          <template #operation="scope">
            <operation :row="scope.row" :col="scope.item" :force-show-button="true" @opertion-click="onErtions" />
          </template>
          <template #operbutton-append>
            <div class="titlestyle">
              可选检验项目
            </div>
          </template>
        </d-table-promote>
      </div>
    </div>
  </d-Dialog>
</template>

<style scoped lang="less">

.titlestyle{
  font-weight: 700;
}
.box{
  width: 100%;
  display: flex;
}
.btn{
  display: flex;
  justify-content: right;
  margin-bottom: 5px;
}
.d-table-from-con{
  row-gap: 0px;
}
</style>